<template>
  <div>
    <!--    按钮-->
    <div style="margin: 10px 5px">
      <el-button type="primary" @click="add">新增</el-button>
      <el-button>其他</el-button>
    </div>
    <!--    搜索框-->
    <div style="margin: 10px 0">
      <el-input v-model="key" placeholder="请输入关键字" style="width: 30%"/>
      <el-button type="primary" style="margin-left: 10px" @click="list">查询</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="ID"/>
      <el-table-column prop="name" label="家居名"/>
      <el-table-column prop="maker" label="厂商"/>
      <el-table-column prop="price" label="价格"/>
      <el-table-column prop="sales" label="销量"/>
      <el-table-column prop="stock" label="库存"/>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column prop="updateTime" label="修改时间"/>
      <el-table-column prop="version" label="version"/>
      <el-table-column fixed="right" label="操作" width="100">
        <template #default="scope">
          <el-button type="text" @click="handleEdit2(scope.row)">编辑</el-button>
          <el-popconfirm title="确认删除吗？" @confirm="handleDel(scope.row.id)">
            <template #reference>
              <el-button type="text">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--    引入分页插件-->
    <div class="demo-pagination-block" style="margin: 20px 0">
      <el-pagination
          :total="total"
          :page-sizes="[2, 5, 10]"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <el-dialog
        v-model="dialogVisible"
        title="提示"
        width="30%"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="家居名" prop="name">
          <el-input v-model="form.name" style="width: 50%; padding-right: 10px"/>
          {{ this.validMsg.name }}
        </el-form-item>
        <el-form-item label="厂商" prop="maker">
          <el-input v-model="form.maker" style="width: 50%; padding-right: 10px"/>
          {{ this.validMsg.maker }}
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" style="width: 50%; padding-right: 10px"/>
          {{ this.validMsg.price }}
        </el-form-item>
        <el-form-item label="销售量" prop="sales">
          <el-input v-model="form.sales" style="width: 50%; padding-right: 10px"/>
          {{ this.validMsg.sales }}
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" style="width: 50%; padding-right: 10px"/>
          {{ this.validMsg.stock }}
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// @ is an alias to /src
// 引入request
import request from "@/utils/request"

export default {
  name: 'HomeView',
  components: {},
  data() { // 数据
    return {
      validMsg: {},
      rules: {
        name: [
          {required: true, message: '请输入家居名称', trigger: 'blur'},
          {min: 3, max: 5, message: '长度应该在3-5之间', trigger: 'blur'}
        ],
        maker: [
          {required: true, message: '请输入制造商名称', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入家居价格', trigger: 'blur'},
          {pattern: /^(([1-9]\d*)|(0)(\.\d+)?)$/, message: "请输入数字", trigger: 'blur'}
        ],
        sales: [
          {required: true, message: '请输入销售量', trigger: 'blur'},
          {pattern: /^([1-9)]\d*)|(0)$/, message: "请输入数字", trigger: 'blur'}
        ],
        stock: [
          {required: true, message: '请输入库存', trigger: 'blur'},
          {pattern: /^([(1-9)]\d*)|(0)$/, message: "请输入数字", trigger: 'blur'}
        ]
      },
      key: '',
      currentPage: 1,// 当前页
      pageSize: 5,
      total: 20,
      form: {},
      dialogVisible: false,
      search: '',
      tableData: []
    }
  },
  created() {
    this.list()
  },
  methods: {
    handleSizeChange(pageSize) {
      // alert(pageSize)
      this.pageSize = pageSize
      this.list()
    },
    handleCurrentChange(currentPage) {
      // alert(currentPage)
      this.currentPage = currentPage
      this.list()
    },
    handleDel(id) {
      // alert("id="+id)
      // alert(typeof id) // number => string 雪花算法精确度
      request.delete("/api/del/" + id).then(
          res => {
            if (res.code === "200") {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
            this.list()
          }
      )
    },
    handleEdit(row) { // 编辑，直接获取行数据
      // console.log("row=",row)
      // console.log("row2:", JSON.stringify(row))
      // console.log("row3:", JSON.parse(JSON.stringify(row)))
      this.dialogVisible = true
      this.form = JSON.parse(JSON.stringify(row))
    },
    handleEdit2(row) { // 编辑，访问数据库
      request.get("/api/find/" + row.id).then(
          res => {
            if (res.code === "200") {
              this.form = res.data
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          }
      )
      this.dialogVisible = true
      this.$refs['form'].resetFields()
      this.validMsg = {}
    },
    add() {
      this.dialogVisible = true
      this.form = {}
      this.$refs['form'].resetFields()
      this.validMsg = {}
    },
    save() {
      this.$refs['form'].validate(valid => {
        // alert(valid)
        valid = true
        if (valid) {
          if (this.form.id) { // 修改
            request.put("/api/update", this.form).then(
                res => {
                  if (res.code === "200") {
                    this.$message({
                      type: 'success',
                      message: '更新成功'
                    })
                  } else {
                    this.$message({
                      type: 'error',
                      message: res.msg
                    })
                  }
                  this.dialogVisible = false
                  this.list()
                }
            )
          } else {
            request.post("/api/save", this.form).then(
                res => {
                  if (res.code === "200") { // 后端添加成功
                    // console.log("result:", res)
                    this.dialogVisible = false
                    this.list()
                    this.$message({
                      type: 'success',
                      message: '添加信息成功'
                    })
                  } else if (res.code === "1001") { // 后端校验添加失败
                    this.validMsg.name = res.data.name
                    this.validMsg.maker = res.data.maker
                    this.validMsg.price = res.data.price
                    this.validMsg.sales = res.data.sales
                    this.validMsg.stock = res.data.stock
                  } else {
                    this.$message({
                      type: 'error',
                      message: '填写内容有误,请重新填写！'
                    })
                  }
                }
            )
          }
        } else {
          this.$message({
            type: 'error',
            message: '填写内容有误,请重新填写！'
          })
        }
      })
    },
    list() {
      // request.get("/api/list").then(
      //     res => {
      //       // console.log("result===", res)
      //       this.tableData = res.data
      //     }
      // )
      request.get("/api/listByConditionPage2", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          key: this.key
        }
      }).then(res => {
        // console.log("res1111=", res.data)
        this.total = res.data.total
        this.tableData = res.data.records
      })
    }
  }
}
</script>
